//
//  WKRegistViewController.m
//  WeKeTang
//
//  Created by ichina on 2017/8/22.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKRegistViewController.h"
#import "WKHomeViewController.h"
#import "WKProfireViewController.h"
#import "WKLoginViewController.h"
#import "NSString+MKNetworkKitAdditions.h"
#import "UIDevice+KZExtension.h"
#import "WKNetworkTools.h"
#import "WKUniversal.h"
#import "WKLoginHandel.h"
#import "UMMobClick/MobClick.h"

@interface WKRegistViewController ()

@property (weak, nonatomic) IBOutlet UITextField *TFPhoneNum;
@property (weak, nonatomic) IBOutlet UITextField *TFVerifyCode;
@property (weak, nonatomic) IBOutlet UITextField *TFPassword;
@property (weak, nonatomic) IBOutlet UIButton *BtnVerifyCode;
@property (weak, nonatomic) IBOutlet UIButton *BtnRegist;
@property (weak, nonatomic) IBOutlet UIButton *BtnShowPed;
@property (nonatomic, strong) NSTimer * verifyTimer;
@property (nonatomic, assign) NSInteger verifyCounter;
@property (nonatomic, assign) BOOL pwdStatus;
@property (nonatomic, assign) long verifyCode;
@property (nonatomic, copy) NSString *SESSID;

@end

@implementation WKRegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _verifyCounter = 60;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.pwdStatus = YES;
    self.view.backgroundColor = RGBColor(245, 245, 245);
    [self setupUI];
}
- (void)setupUI{
    
    self.navItem.title = @"注册";
  //  [self setLeftButtonWithImage:@"icon_return" highlightedImage:@"icon_return" target:self action:@selector(backAction)];
    self.BtnRegist.layer.cornerRadius = 2;
    self.BtnRegist.layer.masksToBounds = YES;
    self.BtnVerifyCode.layer.cornerRadius = 2;
    self.BtnVerifyCode.layer.masksToBounds = YES;
    
    
    UIView *leftView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView1.contentMode = UIViewContentModeCenter;
    self.TFPhoneNum.leftView = leftView1;
    self.TFPhoneNum.leftViewMode = UITextFieldViewModeAlways;
    self.TFPhoneNum.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFPhoneNum.layer.borderWidth = 1;
    
    
    UIView *leftView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView2.contentMode = UIViewContentModeCenter;
    self.TFPassword.leftView = leftView2;
    self.TFPassword.leftViewMode = UITextFieldViewModeAlways;
    self.TFPassword.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFPassword.layer.borderWidth = 1;
    
    UIView *leftView3 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 47)];
    leftView3.contentMode = UIViewContentModeCenter;
    self.TFVerifyCode.leftView = leftView3;
    self.TFVerifyCode.leftViewMode = UITextFieldViewModeAlways;
    self.TFVerifyCode.layer.borderColor = [UIColor colorWithHexString:@"#ededed"].CGColor;
    self.TFVerifyCode.layer.borderWidth = 1;
    
    self.TFPhoneNum.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.TFVerifyCode.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.TFPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.navgationBar.hidden = NO;
    [self.navgationBar setBarTintColor:[UIColor whiteColor]];
    self.statusbar.backgroundColor = [UIColor whiteColor];
}
- (void)backAction{
    
    if (_isBinding) {
        
        [self popToViewControllerWithClass:[WKLoginViewController class]];
        
    }else{
         [MobClick profileSignInWithPUID:@"register_back_onclick"];
        [super backAction];
    }
    
}
#pragma mark - 获取验证码
- (IBAction)getVerificationCodeAction:(UIButton *)sender {
    [MobClick profileSignInWithPUID:@"register_getcode"];
    
    if (self.verifyCounter<60) {
        [self showCustomAlertMessage:@"一分钟内不能重复获取验证码"];
        return;
    }
    long verifyCode = [self getRandomNumber:1000 to:9999];
    NSString *callBackStr = [WKUniversal validateMobile:self.TFPhoneNum.text];
    if (callBackStr) {
        [self showCustomAlertMessage:callBackStr];
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"smsnew" forKey:@"commandid"];
    [para setObject:self.TFPhoneNum.text forKey:@"mobile"];
    [para setObject:_S(@"%.0ld",verifyCode) forKey:@"content"];
    [para setObject:@"1" forKey:@"type"];
    NSLog(@"注册页面验证码：%ld",verifyCode);
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"获取中..." completionHandler:^(id responseObject) {
//        NSDictionary *dict = [responseObject mj_JSONObject];
//        NSLog(@"获取验证码%@",dict[@"head"]);
    } errorHandler:^(NSError *error) {
        [weakSelf showCustomAlertMessage:@"网络错误"];
        
    } finishHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *dic  = dict[@"head"];
        NSString *statuscode = dic[@"statuscode"];
        
        [weakSelf showCustomAlertMessage:@"验证码已发送"];
        NSLog(@"获取验证码%@",dict);
        if ([statuscode intValue] ==100) {
            [weakSelf startTimer];
            weakSelf.verifyCode = verifyCode;
        }else if([statuscode intValue] ==999){
            [self showCustomAlertMessage:@"该手机号已被其他用户使用"];
            
        }
    }];
     NSLog(@"%ld",self.verifyCode);
}

#pragma mark - 显示或隐藏密码
- (IBAction)showPasswordAction:(UIButton *)sender {
    
    self.pwdStatus = !self.pwdStatus;
    self.TFPassword.secureTextEntry = self.pwdStatus;
    [self.BtnShowPed setImage:(self.pwdStatus?IMG(@"icon_invisible.png"):IMG(@"icon_pesswordvisible.png")) forState:UIControlStateNormal];
}
#pragma mark - 注册
- (IBAction)registAction:(UIButton *)sender {
    [MobClick profileSignInWithPUID:@"register_complete"];
    NSString * callBackStr = [WKUniversal validateMobile:self.TFPhoneNum.text];
    if (callBackStr) {
        [self showCustomAlertMessage:callBackStr];
        return;
    }
    if (isExistString(self.TFVerifyCode.text)) {
        [self showCustomAlertMessage:@"验证码不能为空"];
        return;
    }
    
    if ([self.TFPassword.text length]<6 || [self.TFPassword.text length]>18) {
        [self showCustomAlertMessage:@"密码长度不合法"];
        return;
    }
    if (![_S(@"%.0ld",self.verifyCode) isEqualToString:self.TFVerifyCode.text] ) {
        [self showCustomAlertMessage:@"您输入的验证码有误，请从新输入!"];
        return;
    }
    __weak typeof(self) weakSelf = self;
    
    if (_isBinding) {
        //第三方登录注册接口
        NSMutableDictionary *para = [NSMutableDictionary dictionary];
        [para setObject:@"register" forKey:@"commandid"];
        [para setObject:self.TFPhoneNum.text forKey:@"account"];
        [para setObject:self.TFPassword.text forKey:@"password"];
        [para setObject:self.TFPhoneNum.text forKey:@"mobile"];
        [para setObject:@"1" forKey:@"phonevalid"];
        [para setObject:kChannel forKey:@"channel"];
        [para setObject:self.openid forKey:@"openid"];
        [para setObject:self.site forKey:@"site"];
        [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
        [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"注册中..." completionHandler:^(id responseObject) {
            
        } errorHandler:^(NSError *error) {
             [weakSelf showCustomAlertMessage:@"网络错误"];
        } finishHandler:^(id responseObject) {
            NSDictionary *dict = [responseObject mj_JSONObject];
            NSLog(@"三方登录注册：%@",dict);
            NSDictionary *dic  = dict[@"head"];
            NSString *statuscode = dic[@"statuscode"];
            if ([statuscode intValue] == 100) {
                [weakSelf showCustomAlertMessage:@"注册成功"];
                //调第三方登录接口
                [weakSelf loadThirdLogin];
            }
        }];
        
    }else{
        //直接注册接口
        NSMutableDictionary *para = [NSMutableDictionary dictionary];
        [para setObject:self.TFPhoneNum.text forKey:@"account"];
        [para setObject:self.TFPassword.text forKey:@"password"];
        [para setObject:self.TFPhoneNum.text forKey:@"mobile"];
        [para setObject:@"1" forKey:@"phonevalid"];
        [para setObject:@"register" forKey:@"commandid"];
        [para setObject:kChannel forKey:@"channel"];
        
        [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
        [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"注册中..." completionHandler:^(id responseObject) {
            
            NSDictionary *dict = [responseObject mj_JSONObject];
            NSDictionary *dic  = dict[@"head"];
            NSString *statuscode = dic[@"statuscode"];
            if ([statuscode  isEqualToString:@"100"]) {
                [weakSelf showCustomAlertMessage:@"注册成功"];
            }
            
        } errorHandler:^(NSError *error) {
            
            [weakSelf showCustomAlertMessage:@"网络错误"];
            
        } finishHandler:^(id responseObject) {
            
            NSDictionary *dict = [responseObject mj_JSONObject];
            NSLog(@"直接注册：%@",dict);
            NSDictionary *dic  = dict[@"head"];
            NSString *statuscode = dic[@"statuscode"];
            //注册成功调取登录接口
            if ([statuscode  isEqualToString:@"100"]) {
                [weakSelf showCustomAlertMessage:@"注册成功"];
                //调登录接口
                [weakSelf loadLogin];
            }
        }];

    }
    
}
#pragma mark - 注册成功后调登录接口
- (void)loadLogin{
    
    [MobClick profileSignInWithPUID:@"playerID"];//启动友盟账号统计
    __weak typeof(self) weakSelf = self;
    NSDate *date = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyyMMddhhmmss"];
    NSString *timestamp = [dateformatter stringFromDate:date];
    
    NSString *deviceID = mydeviceUniqueIdentifier();
    NSString *version =[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSString *mac= [WKUniversal macaddress];
    
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:self.TFPhoneNum.text forKey:@"account"];
    [para setObject:self.TFPassword.text forKey:@"password"];
    [para setObject:timestamp   forKey:@"timestamp"];
    [para setObject:@"1" forKey:@"sequenceid"];
    [para setObject:@"login" forKey:@"commandid"];
    [para setObject:version forKey:@"version"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:deviceID forKey:@"deviceid"];
    
    [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain tip:@"登录中..." completionHandler:^(id responseObject) {
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSLog(@"登录：%@",dict);
    } errorHandler:^(NSError *error) {
        
        [weakSelf showCustomAlertMessage:@"网络错误"];
        
    } finishHandler:^(id responseObject) {
        
        NSArray * cookieArr = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];//获取cookie
        for (NSHTTPCookie * cookie in cookieArr) {          //遍历cookie
            if ([cookie.name isEqualToString:@"PHPSESSID"]) {
                self.SESSID = cookie.value;
            }
        }
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *dicBody = dict[@"body"];
        NSMutableDictionary *saveDic = [NSMutableDictionary dictionary];
        [saveDic setObject:dicBody[@"userid"] forKey:@"userid"];
        [saveDic setObject:dicBody[@"avatar"] forKey:@"avatar"];
        [saveDic setObject:dicBody[@"account"] forKey:@"account"];
        [saveDic setObject:dicBody[@"nickname"] forKey:@"nickname"];
        [saveDic setObject:self.SESSID forKey:@"SESSID"];
       [saveDic setObject:dicBody[@"hostdate"] forKey:@"hostdate"];
        
        NSDictionary *dicHead = dict[@"head"];
        NSLog(@"直接登录接口：%@",dicHead[@"statuscode"]);
        if ([dicHead[@"statuscode"] intValue] == 100) {
            [self showCustomAlertMessage:@"登录成功"];
            //登录成功后保存账号和密码
            [[NSUserDefaults standardUserDefaults]setObject:self.TFPassword.text forKey:@"password"];
            [[NSUserDefaults standardUserDefaults]setObject:self.TFPhoneNum.text forKey:@"account"];
            [[NSUserDefaults standardUserDefaults]setObject:self.TFPassword.text forKey:@"psd"];
            [[NSUserDefaults standardUserDefaults]synchronize];
             [WKLoginHandel saveLoginDataWithDict:saveDic.mutableCopy];
            //登录成功
            WKHomeViewController *mainVC = [[WKHomeViewController alloc] init];
            mainVC.userId = dicBody[@"userid"];
            WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:mainVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
        }
        
    }];
}
#pragma mark - 第三方登录注册成功之后 调三方登录接口
- (void)loadThirdLogin{
    
    __weak typeof(self) weakSelf = self;
    NSString *version =[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSString *mac= [WKUniversal macaddress];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:@"openlogin" forKey:@"commandid"];
    [para setObject:self.site forKey:@"site"];
    [para setObject:mac forKey:@"mac"];
    [para setObject:version forKey:@"version"];
     [[WKNetworkTools shareManger] setHttpMethod:@"POST"];
    [[WKNetworkTools shareManger]RunRequest:para path:kServerDomain completionHandler:^(id responseObject) {
        
    } errorHandler:^(NSError *error) {
         [weakSelf showCustomAlertMessage:@"网络错误"];
    } finishHandler:^(id responseObject) {
        NSArray * cookieArr = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];//获取cookie
        for (NSHTTPCookie * cookie in cookieArr) {          //遍历cookie
            if ([cookie.name isEqualToString:@"PHPSESSID"]) {
                self.SESSID = cookie.value;
            }
        }
        NSDictionary *dict = [responseObject mj_JSONObject];
        NSDictionary *dicBody = dict[@"body"];
        NSMutableDictionary *saveDic = [NSMutableDictionary dictionary];
        [saveDic setObject:dicBody[@"userid"] forKey:@"userid"];
        [saveDic setObject:dicBody[@"avatar"] forKey:@"avatar"];
        [saveDic setObject:dicBody[@"account"] forKey:@"account"];
        [saveDic setObject:dicBody[@"nickname"] forKey:@"nickname"];
        [saveDic setObject:self.SESSID forKey:@"SESSID"];
        [saveDic setObject:dicBody[@"hostdate"] forKey:@"hostdate"];
        NSDictionary *dicHead = dict[@"head"];
        NSLog(@"登录接口：%@",dicHead[@"statuscode"]);
        if ([dicHead[@"statuscode"] intValue] == 100) {
            [self showCustomAlertMessage:@"登录成功"];
            [WKLoginHandel saveLoginDataWithDict:saveDic.mutableCopy];
            //登录成功
            WKHomeViewController *mainVC = [[WKHomeViewController alloc] init];
            mainVC.userId = dicBody[@"userid"];
            WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:mainVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = navVC;
        }
    }];
}
#pragma mark - 开启定时器
- (void)startTimer{
    self.verifyCounter = 60;
    __weak typeof(self) weakSelf = self;
    if (self.verifyTimer && [self.verifyTimer isValid]) {
        [self.verifyTimer invalidate];
    }
    self.verifyTimer = [NSTimer scheduledTimerWithTimeInterval:1 block:^(NSTimer * _Nonnull timer) {
        weakSelf.verifyCounter--;
        if (weakSelf.verifyCounter<=0) {
            [weakSelf stopTimer];
        }
        else{
            [weakSelf.BtnVerifyCode setTitle:_S(@"%ld秒后重试",weakSelf.verifyCounter) forState:UIControlStateNormal];
        }
    } repeats:YES];
}
- (void)stopTimer{
    if (self.verifyTimer && [self.verifyTimer isValid]) {
        [self.verifyTimer invalidate];
        self.verifyTimer = nil;
    }
    self.verifyCounter = 60;
    [self.BtnVerifyCode setTitle:@"获取验证码" forState:UIControlStateNormal];
}
- (long)getRandomNumber:(long)from to:(long)to{
    return (long)(from + (arc4random() % (to - from + 1)));
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view resignFirstResponder];
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
